package 多线程.线程同步;

/**
 * 线程不安全：存在资源被同时调用的情况
 */

class Unsafe implements Runnable {
    //票数
    private int ticketNum = 10;
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            test();
        }

    }

    //线程不安全，未同步
    private void test() {
        if (ticketNum <= 0) {
            flag = false;
            return;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "卖出一张票；剩余票数" + ticketNum--);
    }

    public static void main(String[] args) {
        //一个资源
        Unsafe w = new Unsafe();
        //多个代理（多个线程操作同一资源）
        new Thread(w, "一号窗口").start();
        new Thread(w, "二号窗口").start();
        new Thread(w, "三号窗口").start();


    }

}
